package parser;

import antlr.RecognitionException;
import antlr.Token;
import java.util.*;
import java.math.*;
import java.io.PrintStream;

class NameTable {
    
    static Map<String, Integer> table = new HashMap<String, Integer>();
    static List<String> names = new ArrayList<String>();
    static Map<String, Integer> operators = new HashMap<String, Integer>();

    static {
        for (int i = 0; i < StandardNames.names.length; i++) {
            table.put(StandardNames.names[i], i);
            names.add(StandardNames.names[i]);
        }
        for (int i = 0; i < Operators.names.length; i++) {
            operators.put(Operators.names[i], i);
        }
    }
    
    static int getOperatorIndex(String name) {
        return operators.get(name);
    }
       
    static int getIndex(String name) {
        Integer i = table.get(name);
        if (i == null) {
            i = table.size();
            table.put(name, i);
            names.add(name);
        }
        return i;
    }
    
    static Map flipMap(Map m) {
        Map result = new HashMap();
        for (Object o : m.entrySet()) {
            Map.Entry e = (Map.Entry)o;
            result.put(e.getValue(), e.getKey());   
        }
        return result;
    }
    
    
    static void writeString(ByteStream out, String name) {
        int len = name.length();
        out.writeShort(len);
        for (int i = 0; i < len; i++) {
            out.write(name.charAt(i));
        }
        if ((len & 1) != 0) {
            out.write(0);
        }
     }
        
     static void dump(PrintStream out) {
        Map names = flipMap(table);
        int size = names.size();
        out.println("Name Table size: " + (size-256));
        for (int i = 0; i < size-256; i++) {
            out.println("" + i + ": " + (String)names.get(i+256));
        }
    }
        
     static void write(ByteStream out) {
        int size = names.size();
        out.writeShort(size-256);
        for (int i = 256; i < size; i++) {
            writeString(out, (String)names.get(i));
        }
    }
    
    

}
